package cn.wgx.modules.base.web;

import cn.wgx.modules.base.util.Counter;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Api(description = "公共点赞、收藏、点击次数等所有次数", value = "所有需要点赞、收藏、次数的公共方法, 用户ID大于500万，效率会下降")
@RestController
@RequestMapping(value = "api/test")
public class PublicCounter extends BaseController{

    private Map<String, Counter> counter = new HashMap<>();


    @ApiOperation("点赞")
    @RequestMapping(value = "like", method = RequestMethod.GET)
    public Map<String,Object> like(@RequestParam Integer resId, Integer userId,@RequestParam(required = false, defaultValue = "like") String type){
        return returnData(getCounter(type).increment(resId, userId));
    }

    @ApiOperation("取消点赞")
    @RequestMapping(value = "unLike", method = RequestMethod.GET)
    public Map<String,Object> unLike(@RequestParam Integer resId, Integer userId,@RequestParam(required = false, defaultValue = "like") String type){
        return returnData(getCounter(type).unIncrement(resId, userId));
    }

    @ApiOperation("是否点赞")
    @RequestMapping(value = "isLike", method = RequestMethod.GET)
    public Map<String,Object> isLike(@RequestParam Integer resId, Integer userId,@RequestParam(required = false, defaultValue = "like") String type){
        return returnData(getCounter(type).isClick(resId, userId));
    }

    @ApiOperation("获取点赞数")
    @RequestMapping(value = "getCount", method = RequestMethod.GET)
    public Map<String,Object> getCount(@RequestParam Integer resId,@RequestParam(required = false, defaultValue = "like") String type){
        return returnData(getCounter(type).getCount(resId));
    }


    @ApiOperation("获取点赞所有人ID")
    @RequestMapping(value = "getAllUser", method = RequestMethod.GET)
    public Map<String,Object> getAllUser(@RequestParam Integer resId,@RequestParam(required = false, defaultValue = "like") String type){
        return returnData(getCounter(type).getAll(resId));
    }


    @ApiOperation("清除")
    @RequestMapping(value = "clear", method = RequestMethod.GET)
    public Map<String,Object> clear(@RequestParam Integer resId,@RequestParam(required = false, defaultValue = "like") String type){
        return returnData(getCounter(type).clear(resId));
    }



    private Counter getCounter(String key){
        if(counter.containsKey(key)){
            return counter.get(key);
        }
        try {
            counter.put(key, new Counter(key));
        } catch (Exception e) {

        }
        return counter.get(key);
    }
}
